package com.baijiaxing.weixin.family.message.units;

import com.baijiaxing.weixin.family.message.enums.FamilyMessageTypeEnum;
import com.baijiaxing.weixin.family.message.model.FamilyImageMessage;
import com.baijiaxing.weixin.family.message.model.FamilyTextMessage;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.Date;

/**
 * Created by June on 2016/12/18.
 */
public class CreateFamilyImageMessage {

    /**
     * 回复图片消息
     * @param mediaId
     * @param toUser
     * @param fromUserName
     * @return
     */
    public static String replyImage(String mediaId, String toUser, String fromUserName){
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("xml");
        root.addElement("ToUserName").addText(toUser);
        root.addElement("FromUserName").addText(fromUserName);
        root.addElement("CreateTime").addText(String.valueOf(new Date().getTime()));
        root.addElement("MsgType").addText(FamilyMessageTypeEnum.IMAGE.getKey());
        Element imageElement = root.addElement("Image");
        imageElement.addElement("MediaId").addText(mediaId);
        return doc.asXML();
    }


    /***
     * 获取图片对象
     * @param msgXml
     * @return
     * @throws DocumentException
     */
    public static FamilyImageMessage parseImage(String msgXml) throws DocumentException {
        FamilyImageMessage imageMsg = new FamilyImageMessage();
        Document doc = DocumentHelper.parseText(msgXml);
        Element root = doc.getRootElement();
        imageMsg.setToUserName(root.element("ToUserName").getStringValue());
        imageMsg.setFromUserName(root.element("FromUserName").getStringValue());
        imageMsg.setCreateTime(Long.parseLong(root.element("CreateTime").getStringValue()));
        imageMsg.setMsgType(root.element("MsgType").getStringValue());
        imageMsg.setPicUrl(root.element("PicUrl").getStringValue());
        imageMsg.setMsgId(Long.parseLong(root.element("MsgId").getStringValue()));
        imageMsg.setMediaId(root.element("MediaId").getStringValue());
        imageMsg.setAgentID(Integer.valueOf(root.element("AgentID").getStringValue()));
        return imageMsg;
    }
}
